import 'dart:io';

import 'package:json_to_dart/json_to_dart.dart';

typedef RequestHandler = void Function(HttpRequest request);

const String host = "0.0.0.0";
const int port = 8001;

void main() async {
  var server = await HttpServer.bind(host, port);
  var router = Router();

  await for (var request in server) {
    var handler = router.handlers[request.uri.path];
    if (handler == null) {
      request.response
        ..write('Not found, please go to "/"')
        ..close();
    } else {
      Future(() {
        try {
          handler(request);
        }
        catch(exception){
          print(exception);
          request.response
          ..write(exception)
          ..write("Please check your json or queryParameters")
          ..close();
        }
      });
    }
  }
}

class Router {

  Map<String, RequestHandler> handlers = {
    "/": (request) async {
      var indexFileContent = await File("UI/index.html").readAsString();
      request.response
        ..headers.contentType = ContentType.html
        ..write(indexFileContent)
        ..close();
    },
    "/Generate": (request) {

      request.response
      ..headers.add("Access-Control-Allow-Origin", "*")
      ..headers.add("Access-Control-Expose-Headers", "*");

      void writeErrorResult() {
        request.response
          ..write(
            'query parameter "json" is missing.'
            '\n\n'
            'for example: json={"name": "yeganaaa"}&rootClassName=User'
            )
          ..close();
      }

      var queries = request.uri.queryParametersAll;
      var json = queries["json"][0];

      if (json == null) {
        writeErrorResult();
        return;
      }
      var rootClass = (queries["rootClassName"] ?? ["RootClass"])[0];
      var generator = ModelGenerator(rootClass);
      var classes = generator.generateDartClasses(json);
      request.response
        ..write("/*\nAuto generated code by https://github.com/javiercbk/json_to_dart\n")
        ..write("this project cloned to https://gitee.com/yeganaaa/Json2Dart-Generator by yeganaaa@163.com \n")
        ..write("Thank you https://github.com/javiercbk/json_to_dart\n")
        ..write("*/\n\n\n")
        ..write(classes)
        ..close();
    },
  };
}